<template>
  <NuxtLayout class="jikey-layout">
    <Head>
      <Title>UI组件</Title>
    </Head>
    <div class="app-page-edit">
      <el-form ref="formRef" class="app-md-form" :model="modelForm" :rules="rules" label-width="70px">
        <div class="app-md-header">
          <div class="app-md-title">
            <el-form-item label="标题" prop="title">
              <el-input v-model="modelForm.title" maxlength="100" show-word-limit autocomplete="off" placeholder="请输入标题，您可以输入100个字" class="title-input" />
            </el-form-item>
          </div>
          <div class="app-md-action">
            <el-button class="app-md-btn" size="default" type="primary" @click="createData()">发布</el-button>
          </div>
        </div>
        <div id="editor" class="app-md-editor markdown-body">
          <MarkDownEditor v-model="modelForm.content" @change="onChangeMd" />
          <!-- <div class="editor-container" v-html="compiledMarkdown" /> -->
        </div>
        <keep-alive>
          <ClientOnly>
            <el-drawer v-model="drawer" class="app-md-drawer-wrap">
              <div class="app-md-drawer">
                <el-collapse v-model="activeCollapse" class="app-aside-collapse">
                  <el-collapse-item title="版本" name="1">
                    <el-row class="app-row-version">
                      <el-col :span="9">
                        <el-form-item v-if="![4, 5, 6].includes(modelForm.navId)" prop="version" label-width="0">
                          <span class="svg-container">
                            <i class="el-icon-user-solid" />
                          </span>
                          <el-radio-group v-model="modelForm.version" size="small">
                            <el-radio :label="3" size="large">Vue3</el-radio>
                            <el-radio :label="2" size="large">Vue2</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="15">
                        <el-form-item label="后台语言" prop="backend">
                          <el-select v-model="modelForm.backend" class="w-full" placeholder="请选择后台语言">
                            <el-option v-for="item in state.backendList" :key="item.id" :label="item.backendName" :value="item.id" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-collapse-item>

                  <el-collapse-item title="文章信息" name="2">
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-form-item label="菜单" prop="navId">
                          <el-select v-model="modelForm.navId" default-first-option :multiple-limit="1" :reserve-keyword="false" class="w-full" placeholder="请选择菜单" @change="onChangeNav">
                            <el-option v-for="(item, index) in TopList" :key="index" :label="item.title" :value="item.value" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item v-if="[1, 5, 6].includes(modelForm.navId)" :label="tagLabelName" prop="tags">
                          <el-select v-model="modelForm.tags" default-first-option :multiple-limit="1" :reserve-keyword="false" class="w-full" placeholder="请选择">
                            <el-option v-for="item in state.tagList" :key="item.id" :label="item.tagName" :value="item.id" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-form-item label="Github" prop="github">
                      <el-input v-model="modelForm.github" placeholder="请输入Github" />
                    </el-form-item>
                    <el-form-item label="Gitee" prop="gitee">
                      <el-input v-model="modelForm.gitee" placeholder="请输入Gitee" />
                    </el-form-item>
                    <el-form-item label="主页" prop="homepage">
                      <el-input v-model="modelForm.homepage" placeholder="请输入主页" />
                    </el-form-item>
                    <el-form-item label="作者" prop="author">
                      <el-input v-model="modelForm.author" placeholder="请输入作者" />
                    </el-form-item>
                  </el-collapse-item>

                  <el-collapse-item title="简介" name="3">
                    <el-form-item prop="summary" label-width="0">
                      <el-input v-model="modelForm.summary" :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="200" type="textarea" show-word-limit placeholder="请输入简介" />
                    </el-form-item>
                  </el-collapse-item>

                  <el-collapse-item title="封面图" name="4" class="app-collapse-cover">
                    <el-form-item prop="coverUrl" label-width="0">
                      <Upload id="cover1" v-model:imageUrl="modelForm.coverUrl">
                        <template #tip> 只能上传jpg/png文件，且不超过2MB</template>
                      </Upload>
                    </el-form-item>
                  </el-collapse-item>
                </el-collapse>
                <el-space class="mt-5" :size="15">
                  <el-button @click="handleCancel">取消</el-button>
                  <el-button type="primary" @click="onSave"> 提交</el-button>
                </el-space>
              </div>
            </el-drawer>
          </ClientOnly>
        </keep-alive>
      </el-form>
    </div>
  </NuxtLayout>
</template>
<script setup lang="ts">
import { set } from '@vueuse/core'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { TopList } from '@/config'

const state = reactive<any>({
  // 标签列表
  tagList: [],
  // 后台语言
  backendList: [],
})

const formRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  title: [{ required: true, trigger: 'blur', message: '请输入模板名称' }],
  author: [{ required: true, trigger: 'blur', message: '请输入作者' }],
  // tags: [{ required: true, trigger: 'blur', message: '请选择UI组件' }],
  coverUrl: [{ required: true, trigger: 'change', message: '请上传封面图' }],
})
const modelForm = reactive({
  userId: 1,
  navId: 1,
  categoryId: 0,
  title: '',
  github: '',
  gitee: '',
  homepage: '',
  author: '',
  summary: '',
  tags: 1,
  coverUrl: '',
  md: '',
  content: '',
  version: 3,
  status: 1,
  backend: '',
})
const drawer = ref(false)
const activeCollapse = ref(['1', '2', '3', '4'])
const route = useRoute()
const tagLabelName = computed(() => (modelForm.navId === 1 ? 'UI组件' : '类别'))

// 获取列表
const getTags = async (type = 1) => {
  const { data }: any = await useAsyncData('use_TagsData', () => useTagsData({ type }))
  const rows = data.value.rows
  state.tagList = rows
  modelForm.tags = rows[0].id
}

const init = () => {
  const navId = route.query.nav_id

  if (navId) {
    modelForm.navId = +navId
    getTags(+navId)
  }
}

init()

// 后台语言列表
const getBackend = async () => {
  const { data }: any = await useAsyncData('use_BackendData', () => useBackendData({ type: 1 }))
  state.backendList = data.value.rows
}

getBackend()

const createData = () => {
  set(drawer, true)
}

const onChangeMd = (v: string) => {
  modelForm.md = v
}

const onChangeNav = (nav: number) => {
  nav !== 1 ? (modelForm.tags = 0) : (modelForm.tags = nav)
  getTags(nav)
}

// 取消
const handleCancel = () => {
  handleClose()
}

// 关闭
const handleClose = () => {
  set(drawer, false)
  formRef.value!.resetFields()
}

// 提交前进行业务处理
const handleModelForm = (modelForm: any) => {
  modelForm.tags = state.tagList.filter((tag: any) => modelForm.tags === tag.id)
  modelForm.backend = state.backendList.filter((back: any) => modelForm.backend === back.id)

  return modelForm
}

// 提交
const onSave = () => {
  formRef
    .value!.validate((valid: any) => {
      if (!valid) return

      const data = unref(handleModelForm(modelForm))

      if (!data.github && !data.gitee) {
        ElMessage.error('请输入仓库地址')
        return
      }

      onSubmit(data)
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {})
}

const onSubmit = (data: any) => {
  fetchArticleAdd(data).then((res: any) => {
    res ? handleSuccess() : notice(res?.error || '新增失败，请稍候在试~！', 'error')
  })
}

// 处理成功
const handleSuccess = () => {
  notice('新增成功，页面正在跳转中')
  setTimeout(() => {
    window.location.reload()
  }, 500)
}
</script>
<style lang="scss">
.app-page-admin {
  border: 1px slid #ccc;
}
.app-md-header {
  line-height: 70px;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f6f7f8;
}
.app-md-title {
  flex: 1;
  margin-right: 1%;
}
.app-md-title .title-input {
  width: 100%;
}
.app-md-title .title-input input {
  border: 0;
  box-shadow: none;
}
.app-md-drawer {
  padding: 0 20px;
  .el-collapse-item__content {
    padding-bottom: 8px;
  }
}
.app-md-form .app-md-title .el-form-item,
.app-row-version .el-form-item {
  margin-bottom: 0;
}
.app-md-action {
  .app-md-btn {
    position: relative;
    top: -3px;
  }
}
.app-page-edit {
  .el-drawer__header {
    margin-bottom: 0;
  }
  .el-drawer__body {
    padding-top: 0px;
  }
}
.app-collapse-cover {
  position: relative;
  .el-form-item {
    margin-bottom: 0;
  }
  .el-form-item__content {
    position: static;
    .el-form-item__error {
      top: 15px;
      left: 50px;
    }
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
}
</style>
